package Ms

//
//import (
//	"bytes"
//	"database/sql"
//	"errors"
//	"fmt"
//	"db2s/dataDispos"
//	"db2s/global"
//	"db2s/outPut"
//	"os"
//	"reflect"
//	"runtime"
//	"strconv"
//	"strings"
//	"time"
//)
//
//type AppTableS struct {
//	DB                 map[string]*sql.DB
//	AppType            string
//	ShardName          string
//	LobSwitch          bool
//	IgnoreColumnLength bool
//	Esa                global.EncryptionProperties
//}
//type FullRowsCheckS struct {
//	WriteTextI outPut.Result
//}
//type OdataFixS struct {
//	Schema          string
//	Table           string
//	RowData         string
//	SourceDevice    string
//	DestDevice      string
//	Sqlwhere        string
//	IndexColumnType string
//	ColData         []map[string]string
//	IndexType       string
//	IndexColumn     []string
//	DataFixType     string
//	LogSeq          int64
//	AppTable        AppTableS
//	FullRowsc       FullRowsCheckS
//	FixFileAlterF   *os.File `json:"dataFixAlterF"`
//}
//
//type (
//	Keywords string
//	Event    string
//)
//
//const (
//	ColumnDataSplict Keywords = "/*go actions columnData*/"
//	AlterDataSplict  Keywords = "/*actions Column Type*/"
//)
//
//func (or *OdataFixS) rowsValueConvertDispos(c, v string) string {
//	var tmpcolumnName string
//	if strings.EqualFold(v, "<entry>") {
//		tmpcolumnName = fmt.Sprintf("''")
//	} else if strings.EqualFold(v, "<nil>") {
//		tmpcolumnName = fmt.Sprintf("NULL")
//	} else {
//		//if strings.ToUpper(c) == "DATETIME" {
//		//	tmpcolumnName = fmt.Sprintf("'%v'", v)
//		//	//tmpcolumnName = fmt.Sprintf("TO_DATE('%s','YYYY-MM-DD HH24:MI:SS')", v)
//		//} else if strings.Contains(strings.ToUpper(c), "TIMESTAMP") {
//		//	tmpcolumnName = fmt.Sprintf("'%v'", v)
//		//	//tmpcolumnName = fmt.Sprintf("TO_DATE('%s','YYYY-MM-DD HH24:MI:SS')", v)
//		//} else {
//		tmpcolumnName = fmt.Sprintf("'%v'", v)
//		//}
//	}
//	if strings.HasPrefix(strings.ToUpper(c), "NUMBER") && len(v) == 0 {
//		tmpcolumnName = fmt.Sprintf("NULL")
//	}
//	if (strings.ToUpper(c) == "DATETIME" || strings.ToUpper(c) == "DATE" || strings.Contains(strings.ToUpper(c), "TIMESTAMP")) && len(v) == 0 {
//		tmpcolumnName = fmt.Sprintf("NULL")
//	}
//	return tmpcolumnName
//}
//
//func (or OdataFixS) FixInsertSqlExec(RowData string, ColData []map[string]string, logseq int64) (string, error) {
//	//查询该表的列名和列信息
//	var (
//		insertSql     string
//		buff          bytes.Buffer
//		esaColumnSeq  = make(map[int]int)
//		esaColumnName = make(map[string]int)
//		event         = "[FixInsertSqlExec]"
//		err           error
//	)
//	f := func(s string, d string) []*string {
//		s = fmt.Sprintf("%v%v", s, d)
//		startIndex := 0
//		var e []*string
//		for {
//			index := strings.Index(s[startIndex:], d)
//			if index == -1 {
//				break
//			}
//			line := s[startIndex : startIndex+index]
//			if len(line) == 0 {
//				line = ""
//			}
//			e = append(e, &line)
//			startIndex += index + len(d)
//		}
//		return e
//	}
//	pc, _, _, _ := runtime.Caller(1)
//	callingFunc := runtime.FuncForPC(pc)
//	callFile, callLine := callingFunc.FileLine(pc)
//	callFunc := callingFunc.Name()
//	callFuncInfo := fmt.Sprintf("Call functions %v Call File %v:%v", callFunc, callFile, callLine)
//
//	vlog = fmt.Sprintf("(%d) %v %v table %s.%s starts to generate insert repair statement.", logseq, callFuncInfo, event, or.Schema, or.Table)
//	global.Wlog.Debug(vlog)
//
//	//处理mysql查询时间列时数据带时区问题  2021-01-23 10:16:29 +0800 CST
//	r := f(RowData, string(ColumnDataSplict))
//	var insertValueColumn = make([]string, len(ColData))
//	for _, v := range or.AppTable.Esa.ColumnSlice {
//		esaColumnName[v]++
//	}
//	for k, v := range ColData {
//		if v1, ok := v["columnName"]; ok {
//			insertValueColumn[k] = v1
//			if _, ok1 := esaColumnName[v1]; ok1 {
//				var seq int
//				if seq, err = strconv.Atoi(v["columnSeq"]); err != nil {
//					return "", err
//				}
//				esaColumnSeq[seq-1]++
//			}
//		}
//	}
//	if len(r) != len(ColData) {
//		if or.AppTable.IgnoreColumnLength && len(ColData) > len(r) {
//			global.Wlog.Warn(fmt.Sprintf("(%d) %v %v table %s.%s rows Data length != table column Data. column data is {%v},rows data is {%v}", logseq, callFuncInfo, event, or.Schema, or.Table, ColData, r))
//		} else {
//			global.Wlog.Error(fmt.Sprintf("(%d) %v %v table %s.%s rows Data length != table column Data. column data is {%v},rows data is {%v}", logseq, callFuncInfo, event, or.Schema, or.Table, ColData, r))
//			return "", errors.New(fmt.Sprintf("column length abnormal"))
//		}
//	}
//	for k, v := range r {
//		var s = *v
//		if strings.Contains(s, "\\") {
//			s = strings.ReplaceAll(s, "\\", "\\\\'")
//		}
//		if strings.Contains(s, "'") {
//			s = strings.ReplaceAll(s, "'", "\\'")
//		}
//		if strings.Contains(s, ";") {
//			s = strings.ReplaceAll(s, ";", "\\;")
//		}
//		columnVal := or.rowsValueConvertDispos(ColData[k]["dataType"], s)
//		if _, ok := esaColumnSeq[k]; ok && len(or.AppTable.Esa.LockFuncName) > 0 {
//			columnVal = fmt.Sprintf("%v.%v(%v)", or.Schema, or.AppTable.Esa.LockFuncName, columnVal)
//		}
//		buff.WriteString(fmt.Sprintf("%s%s", columnVal, global.DataColumnsSplist))
//	}
//	sf := buff.String()
//	if strings.HasSuffix(sf, global.DataColumnsSplist) {
//		sf = sf[:len(sf)-len(global.DataColumnsSplist)]
//	}
//	insertSql = sf
//	buff.Reset()
//	vlog = fmt.Sprintf("(%d) %v %v The insert repair statement of table a is generated. result is {%v}", logseq, callFuncInfo, event, insertSql)
//	global.Wlog.Debug(vlog)
//	return insertSql, nil
//}
//
///*
//表的列类型处理
//*/
//func (or *OdataFixS) tableColumnDispos(colData []map[string]string, indexColumn []string, indexType string) ([]string, map[string]string) {
//	var (
//		FB  []string
//		acc = make(map[string]string) //判断特殊数据类型
//	)
//	for _, i := range colData {
//		if indexType == "pri" || indexType == "uni" {
//			for _, v := range indexColumn {
//				if strings.EqualFold(v, i["columnName"]) {
//					FB = append(FB, i["columnSeq"])
//				}
//			}
//		} else if indexType == "mui" {
//			FB = append(FB, i["columnName"])
//		}
//		if strings.HasPrefix(i["dataType"], "double(") {
//			acc["double"] = i["columnName"]
//		}
//	}
//	return FB, acc
//}
//func (or *OdataFixS) tableColumnConvertDispos(c, v string, F map[string]string) string {
//	if v == "<nil>" {
//		return fmt.Sprintf(" %s is null ", c)
//	}
//	if v == "<entry>" {
//		return fmt.Sprintf(" %s = ''", c)
//	}
//	if c == F["double"] {
//		return fmt.Sprintf("  concat(%s,'') = '%s'", c, v)
//	}
//	return fmt.Sprintf(" \"%s\" = '%s' ", c, v)
//}
//
//func (or *OdataFixS) FixDeleteSqlExec(RowData string, colData []map[string]string, IndexType string, IndexColumn []string, logseq int64) (string, error) {
//	var (
//		deleteSql, deleteSqlWhere string
//		AS                        []string
//		event                     = "[FixDeleteSqlExec]"
//	)
//	pc, _, _, _ := runtime.Caller(1)
//	callingFunc := runtime.FuncForPC(pc)
//	callFile, callLine := callingFunc.FileLine(pc)
//	callFunc := callingFunc.Name()
//	callFuncInfo := fmt.Sprintf("Call functions %v Call File %v:%v", callFunc, callFile, callLine)
//	vlog = fmt.Sprintf("(%d) %v %v table %s.%s starts to generate delete repair statement.", logseq, callFuncInfo, event, or.Schema, or.Table)
//	global.Wlog.Debug(vlog)
//
//	FB, F := or.tableColumnDispos(colData, IndexColumn, IndexType)
//	for k, v := range strings.Split(RowData, string(ColumnDataSplict)) {
//		if strings.Contains(v, "'") {
//			v = strings.ReplaceAll(v, "'", "\\'")
//		}
//		if IndexType == "mui" {
//			AS = append(AS, or.tableColumnConvertDispos(FB[k+1], v, F))
//		} else if IndexType == "pri" || IndexType == "uni" {
//			for l, I := range FB {
//				if I == strconv.Itoa(k+1) {
//					AS = append(AS, or.tableColumnConvertDispos(IndexColumn[l], v, F))
//				}
//			}
//		}
//	}
//	if deleteSqlWhere = strings.Join(AS, " and "); len(deleteSqlWhere) > 0 {
//		deleteSql = fmt.Sprintf("delete from `%s`.`%s` where %s;", or.Schema, or.Table, deleteSqlWhere)
//	}
//	global.Wlog.Debug(fmt.Sprintf("(%d) %v %v Generate delete statement successfully, sql is %s", logseq, callFuncInfo, event, deleteSql))
//	return deleteSql, nil
//}
//
//func (or *OdataFixS) FixAlterIndexSqlExec(indexName any, alterType string, si map[string][]string, logseq int64) []string {
//	var (
//		sqlS   []string
//		indexS []string
//		event  = "[FixAlterIndexSqlExec]"
//	)
//	pc, _, _, _ := runtime.Caller(1)
//	callingFunc := runtime.FuncForPC(pc)
//	callFile, callLine := callingFunc.FileLine(pc)
//	callFunc := callingFunc.Name()
//	callFuncInfo := fmt.Sprintf("Call functions %v Call File %v:%v", callFunc, callFile, callLine)
//	vlog = fmt.Sprintf("(%d) %v %v Start generating index repair statements for table %v.%v.", logseq, callFuncInfo, event, or.Schema, or.Table)
//	global.Wlog.Debug(vlog)
//
//	switch fmt.Sprintf("%v", reflect.TypeOf(indexName)) {
//	case "string":
//		indexS = []string{indexName.(string)}
//	case "[]string":
//		for _, v := range indexName.([]string) {
//			indexS = append(indexS, v)
//		}
//	}
//	for _, v := range indexS {
//		var c []string
//		for _, vi := range si[v] {
//			if len(strings.Split(vi, string(AlterDataSplict))) > 0 {
//				c = append(c, strings.TrimSpace(strings.Split(vi, string(AlterDataSplict))[0]))
//			}
//		}
//		if strings.EqualFold(alterType, "add") {
//			switch or.IndexType {
//			case "pri":
//				sqlS = append(sqlS, fmt.Sprintf("alter table %s.%s add primary key(`%s`);", or.Schema, or.Table, strings.Join(c, "`,`")))
//			case "uni":
//				sqlS = append(sqlS, fmt.Sprintf("alter table %s.%s add unique index %s(`%s`);", or.Schema, or.Table, v, strings.Join(c, "`,`")))
//			case "mul":
//				sqlS = append(sqlS, fmt.Sprintf("alter table %s.%s add index %s(`%s`);", or.Schema, or.Table, v, strings.Join(c, "`,`")))
//			}
//		} else if strings.EqualFold(alterType, "drop") {
//			switch or.IndexType {
//			case "pri":
//				sqlS = append(sqlS, fmt.Sprintf("alter table %s.%s drop primary key;", or.Schema, or.Table))
//			case "uni":
//				sqlS = append(sqlS, fmt.Sprintf("alter table %s.%s drop index %s;", or.Schema, or.Table, v))
//			case "mul":
//				sqlS = append(sqlS, fmt.Sprintf("alter table %s.%s drop index %s;", or.Schema, or.Table, v))
//			}
//		}
//	}
//	vlog = fmt.Sprintf("(%d) %v %v The index repair statement for table a is completed. result is {%v}", logseq, callFuncInfo, event, sqlS)
//	global.Wlog.Debug(vlog)
//	return sqlS
//}
//
//// GeneralInsertPerfixSql 生产
//func (or OdataFixS) GeneralInsertPerfixSql(s global.GeneralInsertPerfixSqlP) (insertPrefix string) {
//	var (
//		tableName string
//	)
//	if strings.EqualFold(s.TableType, "partition") {
//		tableName = fmt.Sprintf(" \"%v\".\"%v\" PARTITION (\"%v\")", s.Schema, s.Table, s.PartitionName)
//	} else if strings.EqualFold(s.TableType, "single") {
//		tableName = fmt.Sprintf(" \"%v\".\"%v\" ", s.Schema, s.Table)
//	}
//	insertPrefix = fmt.Sprintf("%s ", fmt.Sprintf("INSERT INTO %v (\"%s\") VALUES", tableName, strings.Join(s.InsertColumn, "\",\"")))
//	if or.AppTable.LobSwitch {
//		insertPrefix = fmt.Sprintf("INSERT INTO %v (\"%s\") VALUES (%s)", tableName, strings.Join(s.InsertColumn, "\",\""), strings.Join(s.PlaceholderValue, ","))
//	}
//	return
//}
//
//// ApplyInsert 应用插入sql语句
//func (or OdataFixS) ApplyInsert(s global.ApplySqlP) (err error) {
//	var (
//		setVariables []string
//		event        = "[ApplyInsert]"
//		execTimeout  int64
//	)
//	pc, _, _, _ := runtime.Caller(1)
//	callingFunc := runtime.FuncForPC(pc)
//	callFile, callLine := callingFunc.FileLine(pc)
//	callFunc := callingFunc.Name()
//	callFuncInfo := fmt.Sprintf("Call functions %v Call File %v:%v", callFunc, callFile, callLine)
//	vlog = fmt.Sprintf("(%d) %v %v Table %v.%v starts executing the insert repair statement", or.LogSeq, callFuncInfo, event, or.Schema, or.Table)
//	global.Wlog.Debug(vlog)
//	dispos := dataDispos.InstanceActiveS{Schema: or.Schema, Table: or.Table, SessionSet: setVariables, LobSwitch: or.AppTable.LobSwitch, DB: s.DB["single"]}
//	if len(s.ShardName) == 0 {
//		global.Wlog.Warn(fmt.Sprintf("(%d) %v %v The execution of a sql statement failed. sql is {%v},error is {shardName is entry}", or.LogSeq, callFuncInfo, event, s.ApplySqlGather))
//		for _, v := range s.ApplySqlGather {
//			runtime.SetFinalizer(v, nil)
//		}
//		return nil
//	}
//	if _, err = dispos.TrxInsert(s.ApplySqlGather); err != nil {
//		vlog = fmt.Sprintf("(%d) %v %v The execution of a sql statement failed. sql is {%v},error is {%v}", or.LogSeq, callFuncInfo, event, s.ApplySqlGather, err)
//		global.Wlog.Error(vlog)
//		return err
//	}
//	vlog = fmt.Sprintf("(%d) %v %v A sql statement was executed successfully. sql is {%v}, exec timeout is {%vms}", or.LogSeq, callFuncInfo, event, s.ApplySqlGather, execTimeout)
//	global.Wlog.Debug(vlog)
//	return
//}
//
//// ApplyDelete 应用插入sql语句
//func (or OdataFixS) ApplyDelete(s global.ApplySqlP) (err error) {
//	var (
//		setVariables []string
//		event        = "[ApplyInsert]"
//		execTimeout  int64
//	)
//	pc, _, _, _ := runtime.Caller(1)
//	callingFunc := runtime.FuncForPC(pc)
//	callFile, callLine := callingFunc.FileLine(pc)
//	callFunc := callingFunc.Name()
//	callFuncInfo := fmt.Sprintf("Call functions %v Call File %v:%v", callFunc, callFile, callLine)
//	vlog = fmt.Sprintf("(%d) %v %v Table %v.%v starts executing the delete repair statement", or.LogSeq, callFuncInfo, event, or.Schema, or.Table)
//	global.Wlog.Debug(vlog)
//	dispos := dataDispos.InstanceActiveS{Schema: or.Schema, Table: or.Table, SessionSet: setVariables, LobSwitch: or.AppTable.LobSwitch, DB: s.DB["single"]}
//	if execTimeout, err = dispos.TrxInsert(s.ApplySqlGather); err != nil {
//		vlog = fmt.Sprintf("(%d) %v %v The execution of a sql statement failed. sql is {%v},error is {%v}", or.LogSeq, callFuncInfo, event, s.ApplySqlGather, err)
//		global.Wlog.Error(vlog)
//		return err
//	}
//	vlog = fmt.Sprintf("(%d) %v %v A sql statement was executed successfully. sql is {%v}, exec timeout is {%vms}", or.LogSeq, callFuncInfo, event, s.ApplySqlGather, execTimeout)
//	global.Wlog.Debug(vlog)
//	return
//}
//
//// ApplyAlter 应用插入sql语句
//func (or OdataFixS) ApplyAlter(s global.ApplySqlP) (err error) {
//	var (
//		event       = "[ApplyAlter]"
//		execTimeout int64
//	)
//	pc, _, _, _ := runtime.Caller(1)
//	callingFunc := runtime.FuncForPC(pc)
//	callFile, callLine := callingFunc.FileLine(pc)
//	callFunc := callingFunc.Name()
//	callFuncInfo := fmt.Sprintf("Call functions %v Call File %v:%v", callFunc, callFile, callLine)
//	vlog = fmt.Sprintf("(%d) %v %v Table %v.%v starts executing the alter repair statement", or.LogSeq, callFuncInfo, event, or.Schema, or.Table)
//	global.Wlog.Debug(vlog)
//
//	if strings.HasPrefix(s.ShardName, "partition") {
//		s.ShardName = "single"
//	}
//	global.Wlog.Info(fmt.Sprintf("(%d) %s exec rapir sql info {table info is %v.%v shard info is %v,DB info is %v}", or.LogSeq, "execRapirSql1", or.Schema, or.Table, s.ShardName, s.DB))
//	dispos := dataDispos.InstanceActiveS{DB: s.DB[s.ShardName]}
//	if _, _, err = dispos.TrxAlterUpdate(s.ApplySqlGather); err != nil {
//		vlog = fmt.Sprintf("(%d) %v %v The execution of a sql statement failed. sql is {%v},error is {%v}", or.LogSeq, callFuncInfo, event, s.ApplySqlGather, err)
//		global.Wlog.Error(vlog)
//		return err
//	}
//	vlog = fmt.Sprintf("(%d) %v %v A sql statement was executed successfully. sql is {%v}, exec timeout is {%vms}", or.LogSeq, callFuncInfo, event, s.ApplySqlGather, execTimeout)
//	global.Wlog.Debug(vlog)
//	return nil
//}
//
//// ApplyAnalyze analyze table 收集统计信息
//func (or OdataFixS) ApplyAnalyze() (err error) {
//	//setVariables := []string{fmt.Sprintf("use %s", or.Schema), "set sql_mode=''"}
//	//dispos := dataDispos.DBdataDispos{LogThreadSeq: my.LogSeq, Event: "", SessionSet: setVariables, LobSwitch: my.AppTable.LobSwitch, DB: my.AppTable.DB["single"]}
//	//analyzeTable := fmt.Sprintf("analyze table %s.%s", my.Schema, strings.ToLower(my.Table))
//	//sqlstr := []*string{&analyzeTable}
//	//if _, err = dispos.BeginTrxUpdate(sqlstr); err != nil {
//	//	global.Wlog.Error(fmt.Sprintf("(%d) %s analyze table %s.%s fail. error info is %v", 1, "[analyze table]", my.Schema, my.Table, err))
//	//	return err
//	//}
//	return nil
//}
//
//func (or OdataFixS) WriteDataFix(s global.ApplySqlP) error {
//	var (
//		sqlCommit []*string
//		begin     = "begin"
//		commit    = "commit"
//		event     = "[WriteDataFix]"
//		err       error
//	)
//	pc, _, _, _ := runtime.Caller(1)
//	callingFunc := runtime.FuncForPC(pc)
//	callFile, callLine := callingFunc.FileLine(pc)
//	callFunc := callingFunc.Name()
//	beginTime := time.Now()
//	callFuncInfo := fmt.Sprintf("Call functions %v Call File %v:%v", callFunc, callFile, callLine)
//	vlog = fmt.Sprintf("(%d) %v %v  Start writing repair statements of table %v.%v to the repair file.", or.LogSeq, callFuncInfo, event, or.Schema, or.Table)
//	global.Wlog.Debug(vlog)
//	if len(s.ApplySqlGather) > 0 {
//		sqlCommit = append(sqlCommit, &begin)
//		sqlCommit = append(sqlCommit, s.ApplySqlGather...)
//		sqlCommit = append(sqlCommit, &commit)
//	}
//	if !or.FullRowsc.WriteTextI.AppendWrite("", sqlCommit) {
//		vlog = fmt.Sprintf("(%d) %v %v datafix sql write fail. write sql is {%v},error is {%v}", or.LogSeq, callFuncInfo, event, s.ApplySqlGather, err)
//		global.Wlog.Error(vlog)
//		return errors.New(fmt.Sprintf("datafix sql write fail"))
//	}
//	vlog = fmt.Sprintf("(%d) %v %v Write the repair statement of table %v.%v to the repair file successfully. exec timeOut is {%v}", or.LogSeq, callFuncInfo, event, or.Schema, or.Table, time.Since(beginTime).Milliseconds())
//	global.Wlog.Debug(vlog)
//	return nil
//}
//
//func (or OdataFixS) WriteAlterDataFix(s global.ApplySqlP) error {
//	var (
//		event = "[WriteDataFix]"
//		err   error
//	)
//	pc, _, _, _ := runtime.Caller(1)
//	callingFunc := runtime.FuncForPC(pc)
//	callFile, callLine := callingFunc.FileLine(pc)
//	callFunc := callingFunc.Name()
//	beginTime := time.Now()
//	callFuncInfo := fmt.Sprintf("Call functions %v Call File %v:%v", callFunc, callFile, callLine)
//	vlog = fmt.Sprintf("(%d) %v %v  Start writing repair statements of table %v.%v to the repair file.", or.LogSeq, callFuncInfo, event, or.Schema, or.Table)
//	global.Wlog.Debug(vlog)
//	if !or.FullRowsc.WriteTextI.AppendWrite("", s.ApplySqlGather) {
//		vlog = fmt.Sprintf("(%d) %v %v datafix sql write fail. write sql is {%v},error is {%v}", or.LogSeq, callFuncInfo, event, s.ApplySqlGather, err)
//		global.Wlog.Error(vlog)
//		return errors.New(fmt.Sprintf("datafix sql write fail"))
//	}
//	vlog = fmt.Sprintf("(%d) %v %v Write the repair statement of table %v.%v to the repair file successfully. exec timeOut is {%v}", or.LogSeq, callFuncInfo, event, or.Schema, or.Table, time.Since(beginTime).Milliseconds())
//	global.Wlog.Debug(vlog)
//	return nil
//}
//
//func (or OdataFixS) ApplySql(s global.ApplySqlP) error {
//	if or.DataFixType == "file" {
//		switch or.AppTable.AppType {
//		case "alter":
//			return or.WriteAlterDataFix(s)
//		default:
//			return or.WriteDataFix(s)
//		}
//	} else if or.DataFixType == "table" {
//		switch or.AppTable.AppType {
//		case "insert":
//			return or.ApplyInsert(s)
//		case "delete":
//			return or.ApplyDelete(s)
//		case "update":
//		case "alter":
//			return or.ApplyAlter(s)
//		}
//	} else if or.DataFixType == "no" {
//		runtime.SetFinalizer(s.ApplySqlGather, nil)
//		return nil
//	}
//	return nil
//}
